//
//  XCUSerAccountViewModel.swift
//  小陈微博Swift用纯代码创建
//
//  Created by 小陈 on 16/2/28.
//  Copyright © 2016年 小陈. All rights reserved.
//

import UIKit

class XCUSerAccountViewModel: NSObject {
    
    static let sharedInstance:XCUSerAccountViewModel = XCUSerAccountViewModel()
    
    var userAccount: XCUserAccount?
    // 沙盒的路劲
    let AccountFilePath =  NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/Account.plist")
    
    /// 判断用户是否登录
    var isUserLogin: Bool {
        get{
            return userAccount != nil
        }
    }
    
    override init() {
        super.init()
        
        userAccount = loadUserAccount() // 将解档出来的账号赋值给 UserAccount
    }
    
//    // 单例
    // 3.1 调用XCUserAccountViewModel的方法去加载请求
    func loadAccessToken(code: String,loadAccessTokenCallBack:(error: NSError?) -> () ) {
        
        
    // 3.2 使用XCNetworkTool发起请求获取AccessToken,并且准备闭包
        XCNetworkingTool.sharedInstance.loadAccessToken(code, AccessTokenFinised: { (resposed, error) -> () in
             // 3.7判断请求是否失败
            if error != nil || resposed == nil{
                print("获取AccessToken 请求失败 \(error)")
                return
            }
          
            //3.8字典转模型，并给属性赋值
             self.userAccount = XCUserAccount(dict: resposed!)
      //3.9 将模型保存到沙盒中
         self.saveAccount()
    // 回调获取AccessToken 没有出错
       loadAccessTokenCallBack(error: nil)
            
        })
    }
    
    
    
    
    

    func saveAccount (){
        // 账号不能为空
        if userAccount != nil{
        print("FilePath:\(AccountFilePath)")
        NSKeyedArchiver.archiveRootObject(userAccount!, toFile: AccountFilePath)
        }
    }
    
    
    
    /// 将XCUserAccount 从沙盒中解档出来
    func loadUserAccount() -> XCUserAccount?{
      let account = NSKeyedUnarchiver.unarchiveObjectWithFile(AccountFilePath) as? XCUserAccount
        // 还要判断 AccessToken是否过期，如果过期，说明AccessToken 已经没有用了，就不返回过期的账号
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            print("账号没有过期")
//            print("AccountFilePath : \(AccountFilePath)")
            return account
        }else{
            
        return nil
        }
    }
    
    // MARK: 加载用户数据
    func loadUserInfo(loadUserCallBack: (error:NSError?) ->()){
    
        XCNetworkingTool.sharedInstance.loadUserStatus { (result, error) -> () in
            if error != nil{
                print("XCUSerAccountViewModel: 加载用户数据请求失败\(error)")
            }
            // 请求用户数据成功
//            print("XCUSerAccountViewModel: 加载用户数据请求成功\(result)")
         self.userAccount?.avatar_large = result?["avatar_large"] as? String
            self.userAccount?.screen_name = result?["screen_name"] as? String
            
//print("XCUSerAccountViewModel \( self.userAccount?.avatar_large)\n \( self.userAccount?.screen_name)")
            
            self.saveAccount()
            loadUserCallBack(error: nil)
        }
        
    }

    
}
